package com.xuelang.pipeline.app.resource.util;

import com.alibaba.fastjson2.JSONObject;
import io.kubernetes.client.openapi.models.V1PodCondition;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.repository.init.ResourceReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuyuan.ly
 * @since 2024/7/3 20:38
 */
@Slf4j
public class TektonUtil {

    public static String getTimeString() {
        LocalDateTime now = LocalDateTime.now();
        // 定义时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        // 格式化时间为6位数字符串
        return now.format(formatter);
    }

    public static Date getDateTimeFormat(String timestamp) {
        return Date.from(LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(java.time.ZoneId.systemDefault()).toInstant());
    }

    public static Date getDate2offsetDate(OffsetDateTime completionTime) {
        return Date.from(completionTime.toInstant());
    }

    public static String offsetDateTime2Str(OffsetDateTime startTime) {
        if (null == startTime) {
            return "";
        }
        //默认零时区，手动转换成东8区
        return startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("+8")));
    }

    public static String getPodReadyStatus(List<V1PodCondition> conditions) {
        String result = "";
        if (CollectionUtils.isEmpty(conditions)) {
            return result;
        }
        for (V1PodCondition condition : conditions) {
            if ("Ready".equals(condition.getType())) {
                return condition.getStatus();

            }
        }
        return result;
    }

    public static String getNowTime() {
        LocalDateTime now = LocalDateTime.now();
        // 定义自定义的日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
        // 格式化当前日期和时间
        return now.format(formatter);

    }


    public static String readFileString(String path) {
        StringBuilder contentBuilder = new StringBuilder();
        InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream(path);
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = br.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            log.error("获取模板失败" + e);
            throw new RuntimeException(e);
        }
        return contentBuilder.toString();
    }

    public static HashMap<String, String> parseTaskParamMap2O(String param) {
        JSONObject jsonObject = (JSONObject) JSONObject.parse(param);
        HashMap<String, String> taskParamMap = new HashMap<>();
        for (String key : jsonObject.keySet()) {
            taskParamMap.put(key, jsonObject.getString(key));
        }
        return taskParamMap;
    }

    public static String getBase64(String Str) {
        byte[] encodedBytes = Base64.getEncoder().encode(Str.getBytes());
        // 将编码后的字节数组转换为字符串
        String encodedString = new String(encodedBytes);
        return encodedString;
    }

    public static String[] splitImageNameAndTag(String imageString) {
        // 正则表达式匹配从开头到最后一个"/"的任意字符作为仓库地址，然后是从"/"到":"的任意字符作为镜像名，最后是可选的标签
        Pattern pattern = Pattern.compile("^(.+?)(?:/([^/]+)(?::([^/]+))?)?$");
        Matcher matcher = pattern.matcher(imageString);

        if (matcher.matches()) {
            // 仓库地址，包含从开头到最后一个"/"的部分
            String repo = matcher.group(1);
            // 镜像名（不包含标签），可能是空字符串
            String imageName = matcher.group(2);
            // 标签，如果没有则为null
            String tag = matcher.group(3);

            // 如果存在镜像名，则将其与标签组合（如果标签存在的话），否则直接使用标签
            String fullImageName = imageName != null ? (imageName + (tag != null ? ":" + tag : "")) : (tag != null ? ":" + tag : "");

            // 返回仓库地址和完整的镜像名（包含标签）
            return new String[]{repo, fullImageName.isEmpty() ? "latest" : fullImageName};
        } else {
            throw new IllegalArgumentException("提供的镜像地址格式不正确: " + imageString);
        }
    }

    public static String extractDomainAndPort(String url) {
        try {
            URI uri = new URI(url);
            String host = uri.getHost();
            int port = uri.getPort();
            if (port == -1) {
                // 如果端口是-1，说明URL中没有明确指定端口，返回仅主机名
                return host;
            } else {
                // 如果有端口，返回主机名和端口
                return host + ":" + port;
            }
        } catch (URISyntaxException e) {
            log.info("获取镜像地址失败:", e.getMessage(), e);
            return null; // 如果URL格式不正确，返回null
        }
    }

}
